<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例-头像上传</title>
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <style>
    .thumb-box {
      text-align: center;
      margin-top: 50px;
    }

    .thumb {
      width: 250px;
      height: 250px;
      object-fit: cover;
      border-radius: 50%;
    }
  </style>
</head>

<body>
  <div class="thumb-box">
    <!-- 头像 -->
    <label >
    <img src="./images/cover.jpg" class="img-thumbnail thumb" alt="">
    <div class="mt-2">
      <!-- 文件选择框 -->
      <!-- accept 属性表示可选择的文件类型 -->
      <!-- image/* 表示只允许选择图片类型的文件 -->
      <input type="file" id="iptFile" accept="image/*" style="display: none;">
      <!-- 选择头像图片的按钮 -->
      <button class="btn btn-primary" id="btnChoose">选择 & 上传图片</button>
    </div>
  </label>
  </div>

  <script src="./lib/axios.js"></script>
  <script>
     axios.defaults.baseURL = 'http://www.itcbc.com:3006';
  document.querySelector('.btn-primary').addEventListener('click',()=>{
    document.querySelector('[type=file]').click()
  })
  document.querySelector('[type=file]').addEventListener('change',()=>{
    if (document.querySelector('[type=file]').files.length>0) {
      if (document.querySelector('[type=file]').files[0].size>200*1024) {
        return alert('文件不能超过200Kb')
      }
      const type = ['image/png','image/jpeg']
      if (!type.includes(document.querySelector('[type=file]').files[0].type)) {
        return alert('只能jpg，png')
      }
      console.dir(document.querySelector('[type=file]'));
     let fd = new FormData()
     fd.append('avatar',document.querySelector('[type=file]').files[0])
     axios.post('/api/formdata',fd).then(({data})=>{
      console.log(data);
      document.querySelector('img').src = data.data.filename
     })
    }
   
  })
  </script>
</body>

</html>